import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Modal, Form, Input, Select, InputNumber, DatePicker, message, Row, Col, Tag, Typography, Tooltip, Badge, Dropdown, Menu as AntMenu, Switch, Progress, Statistic } from 'antd';
import BaseTable from '../shared/table/BaseTable.tsx';
import { COUPONS_COLUMNS } from '../shared/table/columns';
import { PlusOutlined, EditOutlined, DeleteOutlined, GiftOutlined, SearchOutlined, MoreOutlined, DollarOutlined, CalendarOutlined, UserOutlined, PercentageOutlined, ReloadOutlined, ExportOutlined, ImportOutlined, QrcodeOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { getErrorMessage, getSuccessMessage, getHttpErrorMessage, PAGES, ERROR_TYPES, SUCCESS_TYPES } from '../utils/i18n';
import { ApiWrapper, InputValidator, ErrorHandler } from '../patches/error-handling-wrapper';

const { Title, Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;

// 创建API包装器实例
const apiWrapper = new ApiWrapper(null, { enableRetry: true, enableLogging: true });

const Coupons = () => {
  const [coupons, setCoupons] = useState([
    {
      id: 1,
      name: '新用户专享',
      code: 'NEW2024',
      type: 'discount',
      value: 20,
      minAmount: 50,
      maxDiscount: 100,
      totalCount: 1000,
      usedCount: 156,
      status: 'active',
      startTime: '2024-01-01 00:00:00',
      endTime: '2024-12-31 23:59:59',
      description: '新用户首次下单享受8折优惠',
      activationCondition: '新用户注册后自动激活，首次下单时可使用',
      createTime: '2024-01-01 10:00:00',
      updateTime: '2024-01-15 14:30:00'
    },
    {
      id: 2,
      name: '满减优惠券',
      code: 'SAVE50',
      type: 'amount',
      value: 10,
      minAmount: 50,
      maxDiscount: 0,
      totalCount: 500,
      usedCount: 89,
      status: 'active',
      startTime: '2024-01-10 00:00:00',
      endTime: '2024-02-10 23:59:59',
      description: '满50减10元优惠券',
      activationCondition: '购买商品满50元后自动激活，立即可用',
      createTime: '2024-01-10 09:30:00',
      updateTime: '2024-01-14 16:20:00'
    },
    {
      id: 3,
      name: '免费配送',
      code: 'FREESHIP',
      type: 'shipping',
      value: 0,
      minAmount: 30,
      maxDiscount: 0,
      totalCount: 2000,
      usedCount: 456,
      status: 'active',
      startTime: '2024-01-01 00:00:00',
      endTime: '2024-03-31 23:59:59',
      description: '满30元免配送费',
      activationCondition: '订单金额满30元时自动激活免邮券',
      createTime: '2024-01-01 12:00:00',
      updateTime: '2024-01-15 10:45:00'
    },
    {
      id: 4,
      name: '周末特惠',
      code: 'WEEKEND15',
      type: 'discount',
      value: 15,
      minAmount: 80,
      maxDiscount: 50,
      totalCount: 300,
      usedCount: 234,
      status: 'expired',
      startTime: '2024-01-01 00:00:00',
      endTime: '2024-01-14 23:59:59',
      description: '周末专享85折优惠',
      activationCondition: '仅限周六、周日购买时激活使用',
      createTime: '2024-01-01 15:20:00',
      updateTime: '2024-01-14 23:59:59'
    },
    {
      id: 5,
      name: '生日特惠',
      code: 'BIRTHDAY30',
      type: 'amount',
      value: 30,
      minAmount: 100,
      maxDiscount: 0,
      totalCount: 100,
      usedCount: 12,
      status: 'inactive',
      startTime: '2024-02-01 00:00:00',
      endTime: '2024-02-29 23:59:59',
      description: '生日月专享满100减30',
      createTime: '2024-01-15 11:30:00',
      updateTime: '2024-01-15 11:30:00'
    }
  ]);

  const [loading, setLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [importLoading, setImportLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCoupon, setEditingCoupon] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');

  const [stats, setStats] = useState({
    totalCoupons: 0,
    activeCoupons: 0,
    totalUsed: 0,
    usageRate: 0
  });

  useEffect(() => {
    calculateStats();
  }, [coupons]);

  const calculateStats = () => {
    const totalCoupons = coupons.length;
    const activeCoupons = coupons.filter(coupon => coupon.status === 'active').length;
    const totalUsed = coupons.reduce((sum, coupon) => sum + coupon.usedCount, 0);
    const totalAvailable = coupons.reduce((sum, coupon) => sum + coupon.totalCount, 0);
    const usageRate = totalAvailable > 0 ? (totalUsed / totalAvailable * 100) : 0;

    setStats({
      totalCoupons,
      activeCoupons,
      totalUsed,
      usageRate
    });
  };

  const getStatusColor = (status) => {
    const colors = {
      active: 'success',
      inactive: 'warning',
      expired: 'error'
    };
    return colors[status] || 'default';
  };

  const getStatusText = (status) => {
    const texts = {
      active: '生效中',
      inactive: '未生效',
      expired: '已过期'
    };
    return texts[status] || status;
  };

  const getTypeColor = (type) => {
    const colors = {
      discount: 'blue',
      amount: 'green',
      shipping: 'orange'
    };
    return colors[type] || 'default';
  };

  const getTypeText = (type) => {
    const texts = {
      discount: '折扣券',
      amount: '满减券',
      shipping: '包邮券'
    };
    return texts[type] || type;
  };

  const getTypeIcon = (type) => {
    const icons = {
      discount: <PercentageOutlined />,
      amount: <DollarOutlined />,
      shipping: <GiftOutlined />
    };
    return icons[type] || <GiftOutlined />;
  };

  const formatCouponValue = (coupon) => {
    if (coupon.type === 'discount') {
      return `${coupon.value}折`;
    } else if (coupon.type === 'amount') {
      return `减¥${coupon.value}`;
    } else if (coupon.type === 'shipping') {
      return '免邮费';
    }
    return coupon.value;
  };

  const getUsageProgress = (coupon) => {
    const percentage = coupon.totalCount > 0 ? (coupon.usedCount / coupon.totalCount * 100) : 0;
    return {
      percentage: Math.round(percentage),
      status: percentage >= 90 ? 'exception' : percentage >= 70 ? 'active' : 'normal'
    };
  };

  const handleEdit = (coupon) => {
    setEditingCoupon(coupon);
    
    // 判断有效期类型
    let validityType = 'custom';
    if (coupon.endTime === '2099-12-31 23:59:59') {
      validityType = 'permanent';
    } else {
      const startDate = dayjs(coupon.startTime);
      const endDate = dayjs(coupon.endTime);
      const diffMonths = endDate.diff(startDate, 'month');
      const diffYears = endDate.diff(startDate, 'year');
      
      if (diffMonths === 3) {
        validityType = '3months';
      } else if (diffMonths === 6) {
        validityType = '6months';
      } else if (diffYears === 1) {
        validityType = '1year';
      }
    }
    
    form.setFieldsValue({
      name: coupon.name,
      code: coupon.code,
      type: coupon.type,
      value: coupon.value,
      minAmount: coupon.minAmount,
      maxDiscount: coupon.maxDiscount,
      totalCount: coupon.totalCount,
      status: coupon.status,
      validityType: validityType,
      dateRange: validityType === 'custom' ? [dayjs(coupon.startTime), dayjs(coupon.endTime)] : null,
      description: coupon.description,
      activationCondition: coupon.activationCondition || ''
    });
    setModalVisible(true);
  };

  const handleDelete = (couponId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个优惠券吗？此操作不可恢复。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setCoupons(coupons.filter(coupon => coupon.id !== couponId));
        message.success('优惠券删除成功');
      }
    });
  };

  const handleExport = async () => {
    try {
      setExportLoading(true);
      const csvContent = "data:text/csv;charset=utf-8," + 
        "优惠券名称,优惠券代码,类型,面值,最低消费,最大优惠,总数量,已使用,状态,开始时间,结束时间\n" +
        filteredCoupons.map(coupon => 
          `${coupon.name},${coupon.code},${coupon.type === 'discount' ? '折扣券' : coupon.type === 'amount' ? '满减券' : '包邮券'},${coupon.value},${coupon.minAmount || 0},${coupon.maxDiscount || 0},${coupon.totalCount},${coupon.usedCount},${coupon.status === 'active' ? '生效中' : coupon.status === 'inactive' ? '未生效' : '已过期'},${coupon.startTime},${coupon.endTime}`
        ).join("\n");
      
      const encodedUri = encodeURI(csvContent);
      const link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", `优惠券列表_${dayjs().format('YYYY-MM-DD')}.csv`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      message.success('导出成功');
    } catch {
      message.error('导出失败');
    } finally {
      setExportLoading(false);
    }
  };

  const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.csv,.xlsx';
    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;
      
      try {
        setImportLoading(true);
        // 这里应该实现文件解析和数据导入逻辑
        await new Promise(resolve => setTimeout(resolve, 2000));
        message.success('导入成功');
      } catch {
        message.error('导入失败');
      } finally {
        setImportLoading(false);
      }
    };
    input.click();
  };

  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      const couponData = {
        ...values
      };
      
      // 处理有效期逻辑
      if (values.validityType === 'custom' && values.dateRange) {
        couponData.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
        couponData.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
      } else {
        // 根据有效期类型设置默认值
        couponData.startTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        switch (values.validityType) {
          case '3months':
            couponData.endTime = dayjs().add(3, 'month').format('YYYY-MM-DD HH:mm:ss');
            break;
          case '6months':
            couponData.endTime = dayjs().add(6, 'month').format('YYYY-MM-DD HH:mm:ss');
            break;
          case '1year':
            couponData.endTime = dayjs().add(1, 'year').format('YYYY-MM-DD HH:mm:ss');
            break;
          case 'permanent':
            couponData.endTime = '2099-12-31 23:59:59';
            break;
          default:
            couponData.endTime = dayjs().add(1, 'year').format('YYYY-MM-DD HH:mm:ss');
        }
      }
      
      // 清理不需要的字段
      delete couponData.dateRange;
      delete couponData.validityType;
      
      if (editingCoupon) {
        // 编辑优惠券
        setCoupons(coupons.map(coupon => 
          coupon.id === editingCoupon.id 
            ? { 
                ...coupon, 
                ...couponData, 
                updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
              }
            : coupon
        ));
        message.success('优惠券信息更新成功');
      } else {
        // 新增优惠券
        const newCoupon = {
          id: Date.now(),
          ...couponData,
          usedCount: 0,
          createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        };
        setCoupons([...coupons, newCoupon]);
        message.success('优惠券添加成功');
      }
      
      setModalVisible(false);
      setEditingCoupon(null);
      form.resetFields();
    } catch (error) {
      console.error('保存失败:', error);
      message.error(getErrorMessage(PAGES.COUPONS, ERROR_TYPES.SAVE_FAILED));
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = (couponId, newStatus) => {
    setCoupons(coupons.map(coupon => 
      coupon.id === couponId 
        ? { 
            ...coupon, 
            status: newStatus,
            updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
          }
        : coupon
    ));
    message.success(`优惠券状态已更新为${getStatusText(newStatus)}`);
  };



  const generateCouponCode = () => {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for (let i = 0; i < 8; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    form.setFieldsValue({ code: result });
  };

  const filteredCoupons = coupons.filter(coupon => {
    const matchesSearch = coupon.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         coupon.code.toLowerCase().includes(searchText.toLowerCase()) ||
                         coupon.description.toLowerCase().includes(searchText.toLowerCase());
    const matchesType = typeFilter === 'all' || coupon.type === typeFilter;
    const matchesStatus = statusFilter === 'all' || coupon.status === statusFilter;
    
    return matchesSearch && matchesType && matchesStatus;
  });

  const getActionMenu = (coupon) => (
    <AntMenu>
      <AntMenu.Item key="edit" icon={<EditOutlined />} onClick={() => handleEdit(coupon)}>
        编辑优惠券
      </AntMenu.Item>

      <AntMenu.Item key="qrcode" icon={<QrcodeOutlined />}>
        生成二维码
      </AntMenu.Item>
      <AntMenu.Divider />
      <AntMenu.Item key="active" onClick={() => handleStatusChange(coupon.id, 'active')}>
        设为生效
      </AntMenu.Item>
      <AntMenu.Item key="inactive" onClick={() => handleStatusChange(coupon.id, 'inactive')}>
        设为未生效
      </AntMenu.Item>
      <AntMenu.Divider />
      <AntMenu.Item key="delete" icon={<DeleteOutlined />} danger onClick={() => handleDelete(coupon.id)}>
        删除优惠券
      </AntMenu.Item>
    </AntMenu>
  );

  // 基于统一列配置生成实际渲染列
  const columns = COUPONS_COLUMNS.map(column => {
    if (column.key === 'couponInfo') {
      return {
        ...column,
        render: (_, coupon) => (
          <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
              <Badge 
                count={getTypeIcon(coupon.type)} 
                style={{ backgroundColor: getTypeColor(coupon.type) }}
                size="small"
              />
              <div style={{ fontWeight: 600, fontSize: '14px', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
                {coupon.name}
              </div>
            </div>
            <div style={{ 
              background: '#f5f5f5', 
              padding: '4px 8px', 
              borderRadius: '4px',
              fontSize: '12px',
              fontFamily: 'monospace'
            }}>
              {coupon.code}
            </div>
            <div style={{ color: '#666', fontSize: '11px', whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
              {coupon.description}
            </div>
          </div>
        )
      };
    }
    if (column.key === 'type') {
      return {
        ...column,
        render: (type) => (
          <Tag color={getTypeColor(type)} style={{ borderRadius: '12px', fontSize: '11px' }}>
            {getTypeIcon(type)} {getTypeText(type)}
          </Tag>
        )
      };
    }
    if (column.key === 'value') {
      return {
        ...column,
        render: (_, coupon) => (
          <div>
            <div style={{ fontWeight: 600, color: '#f5222d', fontSize: '14px' }}>
              {formatCouponValue(coupon)}
            </div>
            {coupon.minAmount > 0 && (
              <div style={{ fontSize: '11px', color: '#666' }}>
                满¥{coupon.minAmount}
              </div>
            )}
          </div>
        )
      };
    }
    if (column.key === 'condition') {
      return {
        ...column,
        render: (_, coupon) => (
          <div>
            {coupon.minAmount > 0 && (
              <div style={{ fontSize: '12px', color: '#666' }}>
                满¥{coupon.minAmount}可用
              </div>
            )}
            {coupon.maxDiscount > 0 && (
              <div style={{ fontSize: '11px', color: '#999' }}>
                最高优惠¥{coupon.maxDiscount}
              </div>
            )}
          </div>
        )
      };
    }
    if (column.key === 'validity') {
      return {
        ...column,
        render: (_, coupon) => (
          <div>
            <div style={{ fontSize: '11px', marginBottom: '2px' }}>
              {dayjs(coupon.startTime).format('MM-DD')}
            </div>
            <div style={{ fontSize: '11px', color: '#f5222d' }}>
              {dayjs(coupon.endTime).format('MM-DD')}
            </div>
          </div>
        )
      };
    }
    if (column.key === 'status') {
      return {
        ...column,
        render: (status) => (
          <Tag color={getStatusColor(status)} style={{ borderRadius: '12px', fontSize: '11px' }}>
            {getStatusText(status)}
          </Tag>
        )
      };
    }
    if (column.key === 'action') {
      return {
        ...column,
        render: (_, coupon) => (
          <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
            <Tooltip title="编辑">
              <Button 
                type="primary" 
                size="small" 
                icon={<EditOutlined />}
                onClick={() => handleEdit(coupon)}
              />
            </Tooltip>
            <Dropdown menu={getActionMenu(coupon)} trigger={['click']}>
              <Button size="small" icon={<MoreOutlined />} />
            </Dropdown>
          </div>
        )
      };
    }
    return column;
  });

  return (
    <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      <div style={{ 
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        borderRadius: '16px',
        padding: '24px',
        marginBottom: '24px',
        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
          <div style={{
            width: '64px',
            height: '64px',
            borderRadius: '16px',
            background: 'rgba(255, 255, 255, 0.2)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '28px',
            color: 'white'
          }}>
            <GiftOutlined />
          </div>
          <div>
            <Title level={2} style={{ margin: 0, color: 'white', fontSize: '28px' }}>
              优惠券管理
            </Title>
            <p style={{ margin: '8px 0 0 0', color: 'rgba(255, 255, 255, 0.8)', fontSize: '16px' }}>管理系统优惠券，包括创建、编辑和监控使用情况</p>
          </div>
        </div>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #1890ff 0%, #40a9ff 100%)'
            }} />
            <Statistic
              title="优惠券总数"
              value={stats.totalCoupons}
              prefix={
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '8px',
                  background: 'rgba(24, 144, 255, 0.1)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#1890ff',
                  fontSize: '20px',
                  marginRight: '12px'
                }}>
                  <GiftOutlined />
                </div>
              }
              valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #52c41a 0%, #73d13d 100%)'
            }} />
            <Statistic
              title="生效中"
              value={stats.activeCoupons}
              prefix={
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '8px',
                  background: 'rgba(82, 196, 26, 0.1)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#52c41a',
                  fontSize: '20px',
                  marginRight: '12px'
                }}>
                  <GiftOutlined />
                </div>
              }
              valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #fa8c16 0%, #ffa940 100%)'
            }} />
            <Statistic
              title="总使用次数"
              value={stats.totalUsed}
              prefix={
                <div style={{
                   width: '40px',
                   height: '40px',
                   borderRadius: '8px',
                   background: 'rgba(250, 140, 22, 0.1)',
                   display: 'flex',
                   alignItems: 'center',
                   justifyContent: 'center',
                   color: '#fa8c16',
                   fontSize: '20px',
                   marginRight: '12px'
                 }}>
                   <UserOutlined />
                </div>
              }
              valueStyle={{ color: '#fa8c16', fontSize: '24px', fontWeight: 'bold' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={6}>
          <Card style={{
            borderRadius: '12px',
            border: 'none',
            boxShadow: '0 4px 16px rgba(0, 0, 0, 0.1)',
            background: 'white',
            position: 'relative',
            overflow: 'hidden'
          }}>
            <div style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              height: '4px',
              background: 'linear-gradient(90deg, #faad14 0%, #ffc53d 100%)'
            }} />
            <Statistic
              title="使用率"
              value={stats.usageRate}
              prefix={
                <div style={{
                  width: '40px',
                  height: '40px',
                  borderRadius: '8px',
                  background: 'rgba(250, 173, 20, 0.1)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#faad14',
                  fontSize: '20px',
                  marginRight: '12px'
                }}>
                  <PercentageOutlined />
                </div>
              }
              valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
              precision={1}
              suffix="%"
            />
          </Card>
        </Col>
      </Row>

      {/* 优惠券列表 */}
      <div style={{ 
        background: 'white',
        borderRadius: '16px',
        padding: '24px',
        boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)'
      }}>
        <BaseTable
          columns={columns}
          dataSource={filteredCoupons}
          rowKey="id"
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
        />
      </div>

      {/* 编辑/添加优惠券模态框 */}
      <Modal
        title={editingCoupon ? '编辑优惠券' : '添加优惠券'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false);
          setEditingCoupon(null);
          form.resetFields();
        }}
        confirmLoading={loading}
        width={800}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: '20px' }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="优惠券名称"
                rules={[{ required: true, message: '请输入优惠券名称' }]}
              >
                <Input placeholder="请输入优惠券名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="code"
                label="优惠券代码"
                rules={[{ required: true, message: '请输入优惠券代码' }]}
              >
                <Input 
                  placeholder="请输入优惠券代码" 
                  addonAfter={
                    <Button type="link" size="small" onClick={generateCouponCode}>
                      生成
                    </Button>
                  }
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="type"
                label="优惠券类型"
                rules={[{ required: true, message: '请选择优惠券类型' }]}
              >
                <Select placeholder="请选择优惠券类型">
                  <Option value="discount">折扣券</Option>
                  <Option value="amount">满减券</Option>
                  <Option value="shipping">包邮券</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="value"
                label="优惠值"
                rules={[{ required: true, message: '请输入优惠值' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入优惠值"
                  min={0}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="minAmount"
                label="最低消费"
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入最低消费"
                  min={0}
                  precision={2}
                  addonBefore="¥"
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="maxDiscount"
                label="最高优惠"
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入最高优惠"
                  min={0}
                  precision={2}
                  addonBefore="¥"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="totalCount"
                label="发放数量"
                rules={[{ required: true, message: '请输入发放数量' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入发放数量"
                  min={1}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  <Option value="active">生效中</Option>
                  <Option value="inactive">未生效</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item
            name="activationCondition"
            label="激活条件描述"
            rules={[{ required: true, message: '请输入激活条件描述' }]}
          >
            <TextArea rows={2} placeholder="请描述优惠券的激活条件，如：新用户注册后激活、首次下单后激活等" />
          </Form.Item>
          <Form.Item
            name="validityType"
            label="有效期类型"
            rules={[{ required: true, message: '请选择有效期类型' }]}
          >
            <Select placeholder="请选择有效期类型" onChange={(value) => {
              if (value !== 'custom') {
                form.setFieldsValue({ dateRange: null });
              }
            }}>
              <Option value="3months">激活之日起 3 个月</Option>
              <Option value="6months">激活之日起 6 个月</Option>
              <Option value="1year">购买之日起一年之内</Option>
              <Option value="permanent">长期有效</Option>
              <Option value="custom">自定义时间</Option>
            </Select>
          </Form.Item>
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.validityType !== currentValues.validityType}
          >
            {({ getFieldValue }) => {
              const validityType = getFieldValue('validityType');
              return validityType === 'custom' ? (
                <Form.Item
                  name="dateRange"
                  label="自定义有效期"
                  rules={[{ required: true, message: '请选择有效期' }]}
                >
                  <RangePicker 
                    style={{ width: '100%' }}
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>
          <Form.Item
            name="description"
            label="描述"
            rules={[{ required: true, message: '请输入优惠券描述' }]}
          >
            <TextArea rows={3} placeholder="请输入优惠券描述" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Coupons;